﻿using System;
using NEnsure.Validators;

namespace NEnsure.Requests
{
	public abstract class BaseRequest : IRequest
	{
		private readonly IValidator _validator;

		public BrokenRuleList BrokenRules
		{
			get { return _validator.BrokenRules; }
		}

		public bool IsValid
		{
			get { return Validate(); }
		}

		public BaseRequest()
			: this(new ManualValidator())
		{

		}

		public BaseRequest(IValidator validator)
		{
			if (validator == null)
			{
				throw new ArgumentNullException("validator");
			}

			_validator = validator;
		}

		public bool Execute()
		{
			if (Validate())
			{
				return Go();
			}

			return false;
		}

		private bool Validate()
		{
			_validator.Reset();
			AddRulesToValidator(_validator);

			_validator.EnsureAll();

			return _validator.BrokenRules.Count == 0;
		}

		protected abstract bool Go();

		protected virtual void AddRulesToValidator(IValidator validator)
		{
			
		}
	}
}
